package com.token;

import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JWTFilter extends BasicHttpAuthenticationFilter {

    /**
     * 第二步
     * 是否能进下一步处理
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return true可以访问action了，false则执行onAccessDenied
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        try {
            //得到客户端传过来的令牌
            String token = ((HttpServletRequest) request).getHeader("token");
            //封装
            JWTToken jwtToken = new JWTToken(token);
            //登录:实际是调用LoginRealm里面doGetAuthenticationInfo
            getSubject(request, response).login(jwtToken);
            //判断是否有权限
            String url = ((HttpServletRequest) request).getRequestURI();
            getSubject(request, response).checkPermission(url);

            return true;

        } catch (Exception e) {
            return false;
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse r = (HttpServletResponse) response;
        r.setStatus(401);
        return false;
    }

    /**
     * 用于跨域   第一步
     *
     * @param request
     * @param response
     * @return true可以进下一步isAccessAllowed，如果false则被拦截不能通过
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.addHeader("Access-Control-Allow-Headers", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
        httpServletResponse.addHeader("Access-Control-Expose-Headers", "token");

        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }

        //更新令牌且发送给客户端
        String token = ((HttpServletRequest) request).getHeader("token");
        String newToken = JwtUtil.updateToken(token);
        if (newToken.length() > 0) {
            httpServletResponse.addHeader("token", newToken);
        }

        return super.preHandle(request, response);
    }
}
